<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="js/jquery-1.11.0.min.js"></script>
</head>
<body>

<button onclick="goAdd()">新增</button>
<hr>
<table border="1" width="60%" id="tab">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>money</th>
        <th>操作</th>
    </tr>

<!--    <tr>-->
<!--        <td>1</td>-->
<!--        <td>zs</td>-->
<!--        <td>1000</td>-->
<!--        <td>-->
<!--            <button>修改</button>-->
<!--            <button>删除</button>-->
<!--            <button>转账</button>-->
<!--        </td>-->
<!--    </tr>-->
</table>

<script>
    //查询账户功能封装成方法，方便复用
    function findAll(){
        let url = "/account"
        let params = {}

        $.get(url,params,function (r){
            let code = r.code;
            if (code == 1000){

                //重置数据
                $("#tab").html("<tr>\n" +
                    "        <th>id</th>\n" +
                    "        <th>name</th>\n" +
                    "        <th>money</th>\n" +
                    "        <th>操作</th>\n" +
                    "    </tr>");

                //成功
                let accounts = r.data;
                $.each(accounts,function (idx,account){
                    $("#tab").append("<tr>\n" +
                        "        <td>"+account.id+"</td>\n" +
                        "        <td>"+account.name+"</td>\n" +
                        "        <td>"+account.money+"</td>\n" +
                        "        <td>\n" +
                        "            <button onclick='goUpdate("+account.id+")'>修改</button>\n" +
                        "            <button onclick='del("+account.id+")'>删除</button>\n" +
                        "            <button onclick='goTransfer()'>转账</button>\n" +
                        "        </td>\n" +
                        "    </tr>")
                });
            }else if(code == 2001){
                //没有登录--跳转到登录页面
                location.href = "login.html"
            } else{
                //失败
                let msg = r.msg;
                alert(msg)
            }
        },"json");
    }

    findAll();

    function goUpdate(aid){
        //跳转到修改页面
        location.href = "update.html?aid=" + aid
    }

    function goTransfer(){
        location.href = "transfer.html"
    }

    function goAdd(){
        location.href = "add.html"
    }

    function del(aid){
        let b = confirm("确定删除该账户吗？");
        if (b){
            //发送异步请求删除账户
            $.ajax({
                url:"/account/"+aid,
                type:"DELETE",
                success:function (r){
                    if (r.code == 1000){
                        //重新查询账号信息
                        findAll();
                    }else{
                        alert(r.msg)
                    }
                },
                dataType:"json"
            })
        }
    }
</script>

</body>
</html>